package com.gpsnav.util;

import java.io.*;
import javax.microedition.io.*;
import net.rim.device.api.system.*;

import net.rim.device.api.io.*;

import net.rim.device.api.servicebook.*;
import net.rim.device.api.compress.GZIPInputStream;

public class Communication {
    
    int responseCode,inChar;
    String response;
  
    public int httpConnection_GET(String url){
        InputStream in = null;
        HttpConnection connection = null;
        StringBuffer inBuffer = new StringBuffer();
        
        try{
            url = url + withWiFiSupport();
            
            //System.out.println(url);
            
            connection = (HttpConnection) Connector.open(url);
  
            connection.setRequestProperty("Accept-Encoding", "gzip");
  
            in = connection.openInputStream();
            if(connection.getHeaderField("Content-Encoding") != null && connection.getHeaderField("Content-Encoding").equals("gzip")) {
                in = new GZIPInputStream(in);
            }

            while((inChar = in.read()) != -1) inBuffer.append((char)inChar);
            response = inBuffer.toString();
            responseCode = connection.getResponseCode();
        }catch(Exception e ){
            responseCode = -1;
            System.out.println(e.toString());
        }finally{
            try{
                if(in != null) in.close();
                if(connection != null) connection.close();
            }catch(Exception e){
                System.out.println("Finally: "+e.toString());
            }
        }
        return responseCode;
    }
    
    public int httpConnection_POST(String url, String data){
        InputStream in = null;
        OutputStream out = null;
        HttpConnection connection = null;
        StringBuffer inBuffer = new StringBuffer();
        
        try{
            url = url + withWiFiSupport();
            
                    data = getURLencode(data);
             
            connection = (HttpConnection) Connector.open(url);
            connection.setRequestMethod(HttpConnection.POST);
            connection.setRequestProperty("Content-type", "application/www-form-urlencoded; charset=utf-8");
            connection.setRequestProperty("X-REQUEST", "JSON");
            out = connection.openOutputStream();
            out.write(data.getBytes());
            out.flush();
            responseCode = connection.getResponseCode();
            in = connection.openInputStream();
            while ((inChar = in.read()) != -1) inBuffer.append((char)inChar);
            response = inBuffer.toString();
            return responseCode;
        }catch(Exception e ) { 
            response=e.toString(); 
            responseCode = 500; 
            System.out.println(e.toString());
                        return 500;
        }finally{
            try{
                if(in != null) in.close(); 
                if(out != null) out.close();
                if(connection != null) connection.close();
            }catch(Exception e){
                System.out.println("Finally: "+e.toString());
            }
        }
    }
    
    public String getResponse(){
        return response;
    }
    
    public boolean getGPRSConnectionAvailable(){ 
                if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
                        return true;
                else
                        return (CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_CARRIER));
    }
    
    public String appendConnectionString(){
        ServiceRecord [] ippprecordArray = ServiceBook.getSB().findRecordsByCid("IPPP");
        if(ippprecordArray == null)
            return ";deviceside=true;ConnectionTimeout=600000";
        int numRecords = ippprecordArray.length;
        for(int i=0 ; i<numRecords ; i++){
            ServiceRecord ipppRecord = ippprecordArray[i];
            if(ipppRecord.isValid()){
                if(ipppRecord.getName().equals("IPPP for BIBS"))
                    return ";deviceside=false;ConnectionUID="+ipppRecord.getUid()+";ConnectionTimeout=600000";
            }
        }
        return ";deviceside=true;ConnectionTimeout=600000";
    }
    
    public String withWiFiSupport(){
        if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
            return appendConnectionString() + ";interface=wifi";
        else return appendConnectionString();
    }
    
    public static String getURLencode(String s){
        if (s!=null) {
            StringBuffer tmp = new StringBuffer();
            int i=0;
            try {
                while (true) {
                    int b = (int)s.charAt(i++);
                    if ((b>=0x30 && b<=0x39) || (b>=0x41 && b<=0x5A) || (b>=0x61 && b<=0x7A)) {
                        tmp.append((char)b);
                    }
                    else{
                        tmp.append("%");
                        if (b <= 0xf) tmp.append("0");
                        tmp.append(Integer.toHexString(b));
                    }
                }
            }
            catch (Exception e) {}
            return tmp.toString();
       }
       return null;
    }
} 
